<template>
  <div class="integration-config">
    <el-card class="config-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>系统集成配置</span>
          <div class="header-actions">
            <el-button type="primary" @click="handleAdd">新增配置</el-button>
            <el-button @click="handleRefresh">刷新</el-button>
          </div>
        </div>
      </template>

      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-form :inline="true" :model="searchForm">
          <el-form-item label="系统名称">
            <el-input v-model="searchForm.name" placeholder="请输入系统名称" clearable />
          </el-form-item>
          <el-form-item label="集成类型">
            <el-select v-model="searchForm.type" placeholder="请选择类型" clearable>
              <el-option label="REST API" value="rest" />
              <el-option label="SOAP" value="soap" />
              <el-option label="数据库" value="db" />
              <el-option label="其他" value="other" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
              <el-option label="启用" value="enabled" />
              <el-option label="禁用" value="disabled" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 配置列表 -->
      <el-table :data="configList" border v-loading="loading">
        <el-table-column type="index" width="50" />
        <el-table-column prop="name" label="系统名称" min-width="150" />
        <el-table-column prop="code" label="系统编码" width="120" />
        <el-table-column prop="type" label="集成类型" width="120">
          <template #default="{ row }">
            <el-tag>{{ getTypeLabel(row.type) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="url" label="接口地址" min-width="200" show-overflow-tooltip />
        <el-table-column prop="authType" label="认证方式" width="120">
          <template #default="{ row }">
            <el-tag type="info">{{ getAuthTypeLabel(row.authType) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="syncInterval" label="同步周期" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="'enabled'"
              :inactive-value="'disabled'"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
              <el-button type="primary" link @click="handleTest(row)">测试</el-button>
              <el-button type="primary" link @click="handleSync(row)">同步</el-button>
              <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="page"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 配置表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增配置' : '编辑配置'"
      width="600px"
      destroy-on-close
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        @submit.prevent
      >
        <el-form-item label="系统名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入系统名称" />
        </el-form-item>
        <el-form-item label="系统编码" prop="code">
          <el-input v-model="form.code" placeholder="请输入系统编码" />
        </el-form-item>
        <el-form-item label="集成类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择类型" style="width: 100%">
            <el-option label="REST API" value="rest" />
            <el-option label="SOAP" value="soap" />
            <el-option label="数据库" value="db" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="接口地址" prop="url">
          <el-input v-model="form.url" placeholder="请输入接口地址" />
        </el-form-item>
        <el-form-item label="认证方式" prop="authType">
          <el-select v-model="form.authType" placeholder="请选择认证方式" style="width: 100%">
            <el-option label="Token" value="token" />
            <el-option label="Basic Auth" value="basic" />
            <el-option label="OAuth2" value="oauth2" />
            <el-option label="无" value="none" />
          </el-select>
        </el-form-item>
        <el-form-item label="认证信息" prop="authConfig" v-if="form.authType !== 'none'">
          <el-input
            v-model="form.authConfig"
            type="textarea"
            :rows="3"
            placeholder="请输入认证配置信息（JSON格式）"
          />
        </el-form-item>
        <el-form-item label="同步周期" prop="syncInterval">
          <el-input v-model="form.syncInterval" placeholder="请输入同步周期（分钟）" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="form.status"
            :active-value="'enabled'"
            :inactive-value="'disabled'"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 测试结果对话框 -->
    <el-dialog
      v-model="testDialogVisible"
      title="连接测试结果"
      width="500px"
      destroy-on-close
    >
      <div class="test-result">
        <el-result
          :icon="testResult.success ? 'success' : 'error'"
          :title="testResult.success ? '连接成功' : '连接失败'"
          :sub-title="testResult.message"
        >
          <template #extra>
            <el-button @click="testDialogVisible = false">关闭</el-button>
          </template>
        </el-result>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getSystemList,
  addSystem,
  updateSystem,
  deleteSystem,
  testSystemConnection,
  syncSystemData
} from '@/api/message'

// 搜索表单
const searchForm = reactive({
  name: '',
  type: '',
  status: ''
})

// 列表数据
const configList = ref([])
const loading = ref(false)
const page = ref(1)
const pageSize = ref(20)
const total = ref(0)

// 表单对话框
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)
const form = reactive({
  name: '',
  code: '',
  type: '',
  url: '',
  authType: 'none',
  authConfig: '',
  syncInterval: '',
  status: 'enabled',
  remark: ''
})

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入系统名称', trigger: 'blur' }],
  code: [{ required: true, message: '请输入系统编码', trigger: 'blur' }],
  type: [{ required: true, message: '请选择集成类型', trigger: 'change' }],
  url: [{ required: true, message: '请输入接口地址', trigger: 'blur' }],
  authType: [{ required: true, message: '请选择认证方式', trigger: 'change' }],
  syncInterval: [{ required: true, message: '请输入同步周期', trigger: 'blur' }]
}

// 测试结果对话框
const testDialogVisible = ref(false)
const testResult = reactive({
  success: false,
  message: ''
})

// 加载配置列表
const loadConfigList = async () => {
  try {
    loading.value = true
    const res = await getSystemList({
      page: page.value,
      pageSize: pageSize.value,
      ...searchForm
    })
    configList.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    ElMessage.error('加载配置列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  page.value = 1
  loadConfigList()
}

// 重置搜索
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  handleSearch()
}

// 新增配置
const handleAdd = () => {
  dialogType.value = 'add'
  Object.keys(form).forEach(key => {
    form[key] = key === 'status' ? 'enabled' : key === 'authType' ? 'none' : ''
  })
  dialogVisible.value = true
}

// 编辑配置
const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.keys(form).forEach(key => {
    form[key] = row[key]
  })
  dialogVisible.value = true
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (dialogType.value === 'add') {
          await addSystem(form)
          ElMessage.success('新增配置成功')
        } else {
          await updateSystem(form)
          ElMessage.success('更新配置成功')
        }
        dialogVisible.value = false
        loadConfigList()
      } catch (error) {
        ElMessage.error(dialogType.value === 'add' ? '新增配置失败' : '更新配置失败')
      }
    }
  })
}

// 删除配置
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该配置吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await deleteSystem(row.id)
      ElMessage.success('删除配置成功')
      loadConfigList()
    } catch (error) {
      ElMessage.error('删除配置失败')
    }
  })
}

// 测试连接
const handleTest = async (row) => {
  try {
    const res = await testSystemConnection(row.id)
    testResult.success = res.data.success
    testResult.message = res.data.message
    testDialogVisible.value = true
  } catch (error) {
    ElMessage.error('测试连接失败')
  }
}

// 同步数据
const handleSync = async (row) => {
  try {
    await syncSystemData(row.id)
    ElMessage.success('同步数据成功')
  } catch (error) {
    ElMessage.error('同步数据失败')
  }
}

// 状态变更
const handleStatusChange = async (row) => {
  try {
    await updateSystem({
      id: row.id,
      status: row.status
    })
    ElMessage.success('状态更新成功')
  } catch (error) {
    row.status = row.status === 'enabled' ? 'disabled' : 'enabled'
    ElMessage.error('状态更新失败')
  }
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  loadConfigList()
}

const handleCurrentChange = (val) => {
  page.value = val
  loadConfigList()
}

// 刷新
const handleRefresh = () => {
  loadConfigList()
}

// 工具方法
const getTypeLabel = (type) => {
  const map = { rest: 'REST API', soap: 'SOAP', db: '数据库', other: '其他' }
  return map[type] || type
}

const getAuthTypeLabel = (authType) => {
  const map = { token: 'Token', basic: 'Basic Auth', oauth2: 'OAuth2', none: '无' }
  return map[authType] || authType
}

// 初始化
onMounted(() => {
  loadConfigList()
})
</script>

<style lang="scss" scoped>
.integration-config {
  padding: 20px;
  .config-card {
    .card-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      .header-actions {
        display: flex;
        gap: 10px;
      }
    }
    .search-bar {
      margin-bottom: 20px;
    }
    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
  .test-result {
    padding: 20px;
  }
}
</style> 